/**
 * AI智能表格管理系统 - 简化版JavaScript
 * 作者：俞哲 | 浙江传媒学院 | 指导老师：栗青生
 */

class AITableManagerApp {
    constructor() {
        this.baseUrl = 'http://localhost:8087';
        this.init();
        this.isLoading = false;
        this.deleteStudentId = null;
    }

    /**
     * 初始化应用
     */
    async init() {
        console.log('正在初始化AI智能表格管理系统...');

        // 获取DOM元素
        this.initElements();

        // 绑定事件监听器
        this.bindEventListeners();

        // 确保所有模态框都是隐藏的
        this.hideAllModals();

        // 检查服务器状态
        await this.checkServerStatus();

        // 加载初始数据
        await this.loadStudentsData();
        await this.loadStatistics();

        console.log('系统初始化完成');
    }

    /**
     * 初始化DOM元素
     */
    initElements() {
        this.chatMessages = document.getElementById('chatMessages');
        this.chatInput = document.getElementById('chatInput');
        this.sendBtn = document.getElementById('sendBtn');
        this.studentsTable = document.getElementById('studentsTableBody');
        this.tableLoading = document.getElementById('tableLoading');
        this.tableEmpty = document.getElementById('tableEmpty');

        // 状态指示器元素
        this.statusDot = document.getElementById('statusDot');
        this.statusText = document.getElementById('statusText');
    }

    /**
     * 绑定事件监听器
     */
    bindEventListeners() {
        // 发送消息事件
        if (this.sendBtn) {
            this.sendBtn.addEventListener('click', () => this.sendMessage());
        }

        if (this.chatInput) {
            this.chatInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    this.sendMessage();
                }
            });
        }

        // 按钮事件
        this.bindButtonEvents();

        // 模态框事件
        this.bindModalEvents();

        // 表格点击事件
        this.bindTableEvents();

        // 自动聚焦输入框
        if (this.chatInput) {
            this.chatInput.focus();
        }
    }

    /**
     * 绑定按钮事件
     */
    bindButtonEvents() {
        const buttonEvents = {
            'clearChatBtn': () => this.clearChat(),
            'showExamplesBtn': () => this.showExamples(),
            'refreshDataBtn': () => this.refreshData(),
            'addStudentBtn': () => this.showAddStudentModal(),
            'exportCsvBtn': () => this.exportToCsv(),
            'sortByIdBtn': () => this.sortTableById(),
            'showStatsBtn': () => this.toggleStats()
        };

        Object.entries(buttonEvents).forEach(([id, handler]) => {
            const element = document.getElementById(id);
            if (element) {
                element.addEventListener('click', handler);
            }
        });
    }

    /**
     * 绑定模态框事件
     */
    bindModalEvents() {
        // 示例模态框
        const closeExamplesModal = document.getElementById('closeExamplesModal');
        if (closeExamplesModal) {
            closeExamplesModal.addEventListener('click', () => this.hideExamples());
        }

        // 学生模态框
        const closeStudentModal = document.getElementById('closeStudentModal');
        const cancelStudentBtn = document.getElementById('cancelStudentBtn');
        const studentForm = document.getElementById('studentForm');

        if (closeStudentModal) {
            closeStudentModal.addEventListener('click', () => this.hideStudentModal());
        }
        if (cancelStudentBtn) {
            cancelStudentBtn.addEventListener('click', () => this.hideStudentModal());
        }
        if (studentForm) {
            studentForm.addEventListener('submit', (e) => this.handleStudentFormSubmit(e));
        }

        // 确认删除模态框
        const closeConfirmModal = document.getElementById('closeConfirmModal');
        const cancelDeleteBtn = document.getElementById('cancelDeleteBtn');
        const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');

        if (closeConfirmModal) {
            closeConfirmModal.addEventListener('click', () => this.hideConfirmModal());
        }
        if (cancelDeleteBtn) {
            cancelDeleteBtn.addEventListener('click', () => this.hideConfirmModal());
        }
        if (confirmDeleteBtn) {
            confirmDeleteBtn.addEventListener('click', () => this.confirmDelete());
        }

        // 模态框背景点击关闭
        ['examplesModal', 'studentModal', 'confirmModal'].forEach(modalId => {
            const modal = document.getElementById(modalId);
            if (modal) {
                modal.addEventListener('click', (e) => {
                    if (e.target.id === modalId) {
                        this[`hide${modalId.replace('Modal', '').charAt(0).toUpperCase() + modalId.replace('Modal', '').slice(1)}`]?.() ||
                        this.hideConfirmModal();
                    }
                });
            }
        });
    }

    /**
     * 绑定表格事件
     */
    bindTableEvents() {
        document.addEventListener('click', (e) => {
            // 示例命令点击
            if (e.target.classList.contains('example-item') || e.target.closest('.example-item')) {
                const item = e.target.closest('.example-item') || e.target;
                const command = item.getAttribute('data-command');
                if (command && this.chatInput) {
                    this.chatInput.value = command;
                    this.hideExamples();
                    this.chatInput.focus();
                }
            }

            // 表头排序
            if (e.target.classList.contains('sortable')) {
                const sortField = e.target.getAttribute('data-sort');
                this.sortTable(sortField);
            }

            // 操作按钮
            if (e.target.classList.contains('action-btn-edit')) {
                const studentId = e.target.getAttribute('data-id');
                this.showEditStudentModal(studentId);
            }

            if (e.target.classList.contains('action-btn-delete')) {
                const studentId = e.target.getAttribute('data-id');
                const studentName = e.target.getAttribute('data-name');
                this.showDeleteConfirmModal(studentId, studentName);
            }
        });
    }

    /**
     * 隐藏所有模态框
     */
    hideAllModals() {
        const modals = ['examplesModal', 'studentModal', 'confirmModal'];
        modals.forEach(modalId => {
            const modal = document.getElementById(modalId);
            if (modal) {
                modal.classList.add('hidden');
            }
        });
    }

    /**
     * 检查服务器状态
     */
    async checkServerStatus() {
        try {
            const response = await fetch(`${this.baseUrl}/api/health`);
            const data = await response.json();

            if (data.success) {
                this.updateStatus('connected', 'AI已连接');
            } else {
                this.updateStatus('error', '连接错误');
            }
        } catch (error) {
            console.error('检查服务器状态失败:', error);
            this.updateStatus('error', '连接失败');
        }
    }

    /**
     * 更新状态指示器
     */
    updateStatus(status, text) {
        if (this.statusDot && this.statusText) {
            // 移除所有状态类
            this.statusDot.className = 'status-dot';
            this.statusDot.classList.add(status);
            this.statusText.textContent = text;
        }
    }

    /**
     * 发送消息
     */
    async sendMessage() {
        if (!this.chatInput) return;

        const message = this.chatInput.value.trim();
        if (!message || this.isLoading) return;

        // 显示用户消息
        this.addMessage(message, 'user');

        // 清空输入框并设置加载状态
        this.chatInput.value = '';
        this.setLoading(true);

        try {
            const response = await fetch(`${this.baseUrl}/api/chat`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ message })
            });

            const data = await response.json();

            if (data.success) {
                // 显示AI回复
                this.addMessage(data.response, 'ai', {
                    action: data.action,
                    result: data.result
                });

                // 刷新数据
                if (['insert', 'update', 'delete', 'select'].includes(data.action)) {
                    await this.loadStudentsData();
                    await this.loadStatistics();
                }
            } else {
                this.addMessage(data.response || '处理请求时发生错误', 'ai');
            }
        } catch (error) {
            console.error('发送消息失败:', error);
            this.addMessage('抱歉，发送消息时发生错误，请检查网络连接并重试。', 'ai');
        } finally {
            this.setLoading(false);
        }
    }

    /**
     * 添加消息到聊天窗口
     */
    addMessage(text, type, data = null) {
        if (!this.chatMessages) return;

        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${type}-message`;

        const contentDiv = document.createElement('div');
        contentDiv.className = 'message-content';

        const textDiv = document.createElement('div');
        textDiv.className = 'message-text';
        textDiv.textContent = text;

        contentDiv.appendChild(textDiv);
        messageDiv.appendChild(contentDiv);
        this.chatMessages.appendChild(messageDiv);

        // 滚动到底部
        this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
    }

    /**
     * 设置加载状态
     */
    setLoading(loading) {
        this.isLoading = loading;
        if (this.sendBtn) {
            this.sendBtn.disabled = loading;
            if (loading) {
                this.sendBtn.classList.add('loading');
            } else {
                this.sendBtn.classList.remove('loading');
            }
        }
    }

    /**
     * 清空聊天记录
     */
    clearChat() {
        if (!this.chatMessages) return;

        // 保留系统欢迎消息
        const systemMessage = this.chatMessages.querySelector('.system-message');
        this.chatMessages.innerHTML = '';
        if (systemMessage) {
            this.chatMessages.appendChild(systemMessage);
        }
    }

    /**
     * 刷新数据
     */
    async refreshData() {
        await Promise.all([
            this.loadStudentsData(),
            this.loadStatistics()
        ]);
    }

    /**
     * 加载学生数据
     */
    async loadStudentsData() {
        if (!this.studentsTable) return;

        try {
            if (this.tableLoading) this.tableLoading.style.display = 'flex';
            if (this.tableEmpty) this.tableEmpty.style.display = 'none';

            const response = await fetch(`${this.baseUrl}/api/students`);
            const data = await response.json();

            if (data.success && data.students) {
                this.renderStudentsTable(data.students);
                if (data.students.length === 0 && this.tableEmpty) {
                    this.tableEmpty.style.display = 'flex';
                }
            } else if (this.tableEmpty) {
                this.tableEmpty.style.display = 'flex';
            }
        } catch (error) {
            console.error('加载学生数据失败:', error);
            if (this.tableEmpty) this.tableEmpty.style.display = 'flex';
        } finally {
            if (this.tableLoading) this.tableLoading.style.display = 'none';
        }
    }

    /**
     * 渲染学生表格
     */
    renderStudentsTable(students) {
        if (!this.studentsTable) return;

        this.studentsTable.innerHTML = '';

        students.forEach(student => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${student.id}</td>
                <td>${student.name}</td>
                <td>${student.age}</td>
                <td>${student.major}</td>
                <td>${new Date(student.created_at).toLocaleString('zh-CN')}</td>
                <td>
                    <div class="action-buttons">
                        <button class="action-btn action-btn-edit"
                                data-id="${student.id}"
                                data-name="${student.name}"
                                data-age="${student.age}"
                                data-major="${student.major}">
                            ✏️ 编辑
                        </button>
                        <button class="action-btn action-btn-delete"
                                data-id="${student.id}"
                                data-name="${student.name}">
                            🗑️ 删除
                        </button>
                    </div>
                </td>
            `;
            this.studentsTable.appendChild(row);
        });
    }

    /**
     * 加载统计信息
     */
    async loadStatistics() {
        try {
            const response = await fetch(`${this.baseUrl}/api/statistics`);
            const data = await response.json();

            if (data.success && data.statistics) {
                this.updateStatistics(data.statistics);
            }
        } catch (error) {
            console.error('加载统计信息失败:', error);
        }
    }

    /**
     * 更新统计信息
     */
    updateStatistics(stats) {
        const totalStudents = document.getElementById('totalStudents');
        const totalMajors = document.getElementById('totalMajors');
        const averageAge = document.getElementById('averageAge');

        if (totalStudents) totalStudents.textContent = stats.totalStudents || 0;
        if (totalMajors) totalMajors.textContent = stats.majorDistribution ? stats.majorDistribution.length : 0;
        if (averageAge) averageAge.textContent = stats.averageAge || '-';
    }

    /**
     * 显示示例命令模态框
     */
    showExamples() {
        const modal = document.getElementById('examplesModal');
        if (modal) modal.classList.remove('hidden');
    }

    /**
     * 隐藏示例命令模态框
     */
    hideExamples() {
        const modal = document.getElementById('examplesModal');
        if (modal) modal.classList.add('hidden');
    }

    /**
     * 切换统计信息显示
     */
    toggleStats() {
        const statsPanel = document.getElementById('statsPanel');
        if (statsPanel) {
            const isVisible = !statsPanel.classList.contains('hidden');
            if (isVisible) {
                statsPanel.classList.add('hidden');
            } else {
                statsPanel.classList.remove('hidden');
                this.loadStatistics();
            }
        }
    }

    /**
     * 显示添加学生模态框
     */
    showAddStudentModal() {
        const modal = document.getElementById('studentModal');
        const title = document.getElementById('studentModalTitle');
        const form = document.getElementById('studentForm');
        const editId = document.getElementById('editStudentId');

        if (title) title.textContent = '➕ 添加学生';
        if (editId) editId.value = '';
        if (form) form.reset();
        if (modal) modal.classList.remove('hidden');

        const nameInput = document.getElementById('studentName');
        if (nameInput) nameInput.focus();
    }

    /**
     * 显示编辑学生模态框
     */
    showEditStudentModal(studentId) {
        const editBtn = document.querySelector(`[data-id="${studentId}"].action-btn-edit`);
        if (!editBtn) return;

        const name = editBtn.getAttribute('data-name');
        const age = editBtn.getAttribute('data-age');
        const major = editBtn.getAttribute('data-major');

        const modal = document.getElementById('studentModal');
        const title = document.getElementById('studentModalTitle');
        const editId = document.getElementById('editStudentId');
        const nameInput = document.getElementById('studentName');
        const ageInput = document.getElementById('studentAge');
        const majorInput = document.getElementById('studentMajor');

        if (title) title.textContent = '✏️ 编辑学生';
        if (editId) editId.value = studentId;
        if (nameInput) nameInput.value = name;
        if (ageInput) ageInput.value = age;
        if (majorInput) majorInput.value = major;
        if (modal) modal.classList.remove('hidden');
        if (nameInput) nameInput.focus();
    }

    /**
     * 隐藏学生模态框
     */
    hideStudentModal() {
        const modal = document.getElementById('studentModal');
        if (modal) modal.classList.add('hidden');
    }

    /**
     * 处理学生表单提交
     */
    async handleStudentFormSubmit(e) {
        e.preventDefault();

        const studentId = document.getElementById('editStudentId')?.value;
        const name = document.getElementById('studentName')?.value.trim();
        const age = parseInt(document.getElementById('studentAge')?.value);
        const major = document.getElementById('studentMajor')?.value.trim();

        if (!name || !age || !major) {
            alert('请填写完整的学生信息！');
            return;
        }

        const studentData = { name, age, major };

        try {
            let response;
            if (studentId) {
                response = await this.updateStudent(studentId, studentData);
            } else {
                response = await this.addStudent(studentData);
            }

            if (response.success) {
                this.hideStudentModal();
                await this.loadStudentsData();
                await this.loadStatistics();

                const action = studentId ? '更新' : '添加';
                this.addMessage(`✅ 成功${action}学生：${name}`, 'system');
            } else {
                alert(`操作失败：${response.message || response.error}`);
            }
        } catch (error) {
            console.error('学生表单提交失败:', error);
            alert('操作失败，请重试');
        }
    }

    /**
     * 添加学生
     */
    async addStudent(studentData) {
        const response = await fetch(`${this.baseUrl}/api/students`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(studentData)
        });
        return await response.json();
    }

    /**
     * 更新学生
     */
    async updateStudent(studentId, studentData) {
        const response = await fetch(`${this.baseUrl}/api/students/${studentId}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(studentData)
        });
        return await response.json();
    }

    /**
     * 显示删除确认模态框
     */
    showDeleteConfirmModal(studentId, studentName) {
        this.deleteStudentId = studentId;
        const modal = document.getElementById('confirmModal');
        const message = document.getElementById('confirmMessage');

        if (message) {
            message.textContent = `确定要删除学生"${studentName}"的记录吗？此操作不可撤销。`;
        }
        if (modal) modal.classList.remove('hidden');
    }

    /**
     * 隐藏确认删除模态框
     */
    hideConfirmModal() {
        const modal = document.getElementById('confirmModal');
        if (modal) modal.classList.add('hidden');
        this.deleteStudentId = null;
    }

    /**
     * 确认删除学生
     */
    async confirmDelete() {
        if (!this.deleteStudentId) return;

        try {
            const response = await this.deleteStudent(this.deleteStudentId);

            if (response.success) {
                this.hideConfirmModal();
                await this.loadStudentsData();
                await this.loadStatistics();
                this.addMessage('✅ 学生记录已删除', 'system');
            } else {
                alert(`删除失败：${response.message || response.error}`);
            }
        } catch (error) {
            console.error('删除学生失败:', error);
            alert('删除失败，请重试');
        }
    }

    /**
     * 删除学生
     */
    async deleteStudent(studentId) {
        const response = await fetch(`${this.baseUrl}/api/students/${studentId}`, {
            method: 'DELETE'
        });
        return await response.json();
    }

    /**
     * 按学号排序表格
     */
    sortTableById() {
        this.sortTable('id');
    }

    /**
     * 表格排序功能
     */
    sortTable(field) {
        if (!this.studentsTable) return;

        const rows = Array.from(this.studentsTable.querySelectorAll('tr'));
        const header = document.querySelector(`[data-sort="${field}"]`);

        if (!header) return;

        const currentSort = header.classList.contains('sort-asc') ? 'asc' :
                           header.classList.contains('sort-desc') ? 'desc' : 'none';

        // 清除所有排序状态
        document.querySelectorAll('.sortable').forEach(h => {
            h.classList.remove('sort-asc', 'sort-desc');
        });

        // 确定新的排序方向
        const newSort = currentSort === 'asc' ? 'desc' : 'asc';
        header.classList.add(newSort === 'asc' ? 'sort-asc' : 'sort-desc');

        // 排序逻辑
        rows.sort((a, b) => {
            let aVal, bVal;

            switch (field) {
                case 'id':
                case 'age':
                    aVal = parseInt(a.cells[field === 'id' ? 0 : 2].textContent);
                    bVal = parseInt(b.cells[field === 'id' ? 0 : 2].textContent);
                    break;
                case 'name':
                    aVal = a.cells[1].textContent.toLowerCase();
                    bVal = b.cells[1].textContent.toLowerCase();
                    break;
                case 'major':
                    aVal = a.cells[3].textContent.toLowerCase();
                    bVal = b.cells[3].textContent.toLowerCase();
                    break;
                default:
                    return 0;
            }

            if (aVal < bVal) return newSort === 'asc' ? -1 : 1;
            if (aVal > bVal) return newSort === 'asc' ? 1 : -1;
            return 0;
        });

        // 重新添加排序后的行
        this.studentsTable.innerHTML = '';
        rows.forEach(row => this.studentsTable.appendChild(row));

        // 添加排序消息到聊天
        const sortText = newSort === 'asc' ? '升序' : '降序';
        const fieldText = {
            'id': '学号',
            'name': '姓名',
            'age': '年龄',
            'major': '专业'
        }[field];

        this.addMessage(`📊 表格已按${fieldText}${sortText}排列`, 'system');
    }

    /**
     * 导出CSV文件
     */
    async exportToCsv() {
        try {
            const response = await fetch(`${this.baseUrl}/api/export/csv`);

            if (!response.ok) {
                throw new Error(`导出失败: ${response.status}`);
            }

            // 获取文件名
            const contentDisposition = response.headers.get('Content-Disposition');
            let filename = '学生信息表.csv';
            if (contentDisposition) {
                const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
                if (filenameMatch) {
                    filename = decodeURIComponent(filenameMatch[1].replace(/['"]/g, ''));
                }
            }

            // 创建下载链接
            const blob = await response.blob();
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);

            this.addMessage('📥 CSV文件导出成功！', 'system');
        } catch (error) {
            console.error('导出CSV失败:', error);
            this.addMessage(`❌ 导出失败：${error.message}`, 'system');
        }
    }
}

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    try {
        window.app = new AITableManagerApp();
        console.log('AI智能表格管理系统已启动');
    } catch (error) {
        console.error('系统启动失败:', error);
        alert('系统启动失败，请刷新页面重试');
    }
});

// 全局错误处理
window.addEventListener('error', (event) => {
    console.error('全局错误:', event.error);
});

window.addEventListener('unhandledrejection', (event) => {
    console.error('未处理的Promise拒绝:', event.reason);
});

// 导出类供其他脚本使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = AITableManagerApp;
}